import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { User } from '../entities/user.entity';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.usersService.findByUsername(username);
    if (user && await user.comparePassword(password)) {
      const { password, ...result } = user.toObject();
      return result;
    }
    return null;
  }

  async login(user: any) {
    const payload = { 
      username: user.username, 
      sub: user._id,
      email: user.email 
    };
    
    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user._id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        status: user.status,
      },
    };
  }

  async register(userData: {
    username: string;
    email: string;
    password: string;
    nickname?: string;
  }) {
    const existingUser = await this.usersService.findByUsername(userData.username);
    if (existingUser) {
      throw new UnauthorizedException('用户名已存在');
    }

    const existingEmail = await this.usersService.findByEmail(userData.email);
    if (existingEmail) {
      throw new UnauthorizedException('邮箱已被注册');
    }

    const user = await this.usersService.create(userData);
    return this.login(user);
  }

  async validateToken(token: string): Promise<User | null> {
    try {
      const payload = this.jwtService.verify(token);
      return this.usersService.findById(payload.sub);
    } catch {
      return null;
    }
  }
}
